package bill.study.designPattern.visitor.javagenericsbook;

public class TreeClient {

	public static <T> String toString(Tree<T> t) {
		return t.visit(new Tree.Visitor<T, String>() {

			@Override
			public String branch(String left, String right) {
				return "(" + left + "^" + right + ")";
			}

			@Override
			public String leaf(T elt) {
				return elt.toString();
			}
		});
	}

	public static <N extends Number> double sum(Tree<N> t) {
		return t.visit(new Tree.Visitor<N, Double>() {

			@Override
			public Double branch(Double left, Double right) {
				return left + right;
			}

			@Override
			public Double leaf(N elt) {
				return elt.doubleValue();
			}
		});
	}

	public static void main(String args[]) {
		Tree<Integer> t = Tree.branch(Tree.branch(Tree.leaf(1), Tree.leaf(2)),
				Tree.leaf(3));

		System.out.println(t + " and the sum is " + sum(t));
		assert toString(t).equals("((1^2)^3)");
		assert sum(t) == 6;
	}
}
